import api from "@/utils/api.js"

const msg = (title, duration=1500, mask=false, icon='none')=>{
	//统一提示方便全局修改
	if(Boolean(title) === false){
		return;
	}
	uni.showToast({
		title,
		duration,
		mask,
		icon
	});
}

const prePage = ()=>{
	let pages = getCurrentPages();
	let prePage = pages[pages.length - 2];
	// #ifdef H5
	return prePage;
	// #endif
	return prePage.$vm;
}

const navTo = (url) => {
	uni.navigateTo({
		url
	})
}

const getFileUrl = (url) => {
	if (!url) return ''
	if (/^http.*/i.test(url)) {
		return url;
	} else {
		if (url.indexOf('sys/common/static') == -1) {
			return api.baseUrl + "/sys/common/static/" +  url
		} else {
			return api.baseUrl+ '/' + url
		}
	}
}

const getFileUrlTest = (url) => {
	if (!url) return ''
	let baseUrl = 'https://www.caoss.vip/dcck2/jeecg-boot'
	if (/^http.*/i.test(url)) {
		return url;
	} else {
		if (url.indexOf('sys/common/static') == -1) {
			return baseUrl + "/sys/common/static/" +  url
		} else {
			return baseUrl+ '/' + url
		}
	}
}

const openFile = (id, url) => {
	const key = "filePath"
	return new Promise((resolve, reject) => {
		try {
			let fileValue = uni.getStorageSync(key);
			if (fileValue && fileValue[id]) {
				uni.openDocument({
				  filePath: fileValue[id],
				  fileType: url.split('.').pop(),
				  showMenu: true,
				  success: (res) => {
				    resolve()
				  },
				  fail: (res) => {
				    reject('文件异常')
				  },
				});
			} else {
				if (!fileValue) fileValue = {}
				let httpurl = getFileUrl(url)
				uni.downloadFile({
				  url: httpurl,
				  timeout: 90000,
				  success: function (res) {
				    var filePath = res.tempFilePath;
					fileValue[id] = filePath
					uni.setStorageSync(key, fileValue);
				    uni.openDocument({
				      filePath: filePath,
					  fileType: url.split('.').pop(),
				      showMenu: true,
				      success: function (res) {
				        resolve()
				      },
					  fail: (res) => {
					    reject('文件异常')
					  }
				    });
				  }
				});
			}
		} catch (e) {
			// error
			reject('发生异常')
		}
	})
	
}

const delFile = (id) => {
	const key = "filePath"
	let fileValue = uni.getStorageSync(key);
	console.log(fileValue, fileValue[id], 'fileValues')
	if (fileValue && fileValue[id]) {
		delete fileValue[id]
		uni.setStorageSync(key, fileValue);
	}
}

export default {
	msg,
	prePage,
	navTo,
	getFileUrl,
	openFile,
	delFile
}